package observer;

import java.util.Observer;
import java.util.Observable;

/**
 * 观察者(Observer)模式: 使用Java类库支持的观察者模式 java.util.Observer java.util.Observable
 * 
 * 运行结果: Prievious:,Changed:abc Prievious:abc,Changed:abcd
 * Prievious:abcd,Changed:f
 * 
 * @version 2009-5-6
 * @author Winty(wintys@gmail.com)
 */
public class ObserverTest {
	public static void main(String[] args) {
		Watched watched = new Watched();
		Watcher watcher = new Watcher();
		watched.addObserver(watcher);

		watched.changeData("abc");
		watched.changeData("abcd");
		watched.changeData("abcd");
		watched.changeData("f");
		watched.changeData(null);
		watched.changeData(null);
	}
}

/**
 * 具体被观察者,Observable是抽象被观察者
 */
class Watched extends Observable {
	private String data;

	public Watched() {
		data = "";
	}

	public String retrieveData() {
		return data;
	}

	public void changeData(String data) {
		if (data != null && !this.data.equals(data)) {
			String dt = this.data;// 记录变化前的数据
			this.data = data;

			setChanged();
			notifyObservers(dt);
		}
	}
}

/**
 * 具体观察者,抽象观察者为Observer
 */
class Watcher implements Observer {
	@Override
	public void update(Observable o, Object arg) {
		Watched wathed = (Watched) o;
		String previousData = (String) arg;

		System.out.print("Prievious:" + previousData + ",");
		System.out.println("Changed:" + wathed.retrieveData());
	}

}
